package com.yilin.commons.util;

import com.yilin.commons.encrypt.Base64Util;
import org.springframework.util.StreamUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class StreamUtil {
    /**
     * 读取流数据
     * */
    public static String getBodyString(BufferedReader body){
        String str;
        StringBuilder wholeStr = new StringBuilder();
        try {
            while ((str = body.readLine()) != null) {
                wholeStr.append(str);
            }
            body.close();
            return wholeStr.toString();
        }catch (IOException e) {
            return null;
        }
    }

    public static String getBodyString(InputStream body){
        String bodyData = null;
        try {
            bodyData = StreamUtils.copyToString(body, StandardCharsets.UTF_8);
        } catch (IOException e) {
            return null;
        }
        return bodyData;
    }

    public static boolean isImageFromBase64(String base64Str) {
        if (base64Str == null) return false;
        boolean flag = false;
        try {
            // 获取图片流
            byte[] bytes = Base64Util.base64Decode(base64Str);
            if (bytes==null || bytes.length <= 0) return false;
            BufferedImage bufImg = ImageIO.read(new ByteArrayInputStream(bytes));
            if (null == bufImg) return false;
            flag = true;
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return flag;
    }


}
